from flask import request, current_app
from flask_restx import Resource, Namespace, fields
from app.services.user_interaction_service import UserInteractionService
from app.utils.auth import user_token_required
from app.utils.response import success_response, error_response
from app.utils.validators import validate_required_fields
from . import api

# 创建命名空间
interact_ns = Namespace('interactions', description='用户交互接口')

# 请求模型
interaction_model = interact_ns.model('Interaction', {
    'target_user_id': fields.Integer(required=True, description='目标用户ID')
})

# ----------------- 点赞 -----------------
@interact_ns.route('/like')
class LikeAPI(Resource):
    @interact_ns.expect(interaction_model)
    @user_token_required
    def post(self, current_user):
        is_valid, error_msg = validate_required_fields(['target_user_id'])
        if not is_valid:
            return error_response(error_msg, 400)
        data = request.get_json()
        target_user_id = data.get('target_user_id')
        try:
            record = UserInteractionService.like_user(current_user.id, target_user_id)
            return success_response(record.to_dict(), '点赞成功')
        except Exception as e:
            current_app.logger.error(str(e))
            return error_response(str(e), 500)

@interact_ns.route('/like/<int:record_id>')
class CancelLikeAPI(Resource):
    @user_token_required
    def delete(self, record_id, current_user):
        # 直接根据 record_id 删除点赞记录
        from app.models.user_behavior import UserBehavior
        rec = UserBehavior.query.get(record_id)
        if not rec or rec.user_id != current_user.id or rec.action != UserInteractionService.ACTION_LIKE:
            return error_response('记录不存在', 404)
        from app import db
        db.session.delete(rec)
        db.session.commit()
        return success_response(message='已取消点赞')

@interact_ns.route('/likes')
class LikeListAPI(Resource):
    @user_token_required
    def get(self, current_user):
        page = int(request.args.get('page', 1))
        limit = int(request.args.get('limit', 10))
        records, total = UserInteractionService.get_likes(current_user.id, page, limit)
        return success_response({'items': records, 'total': total}, '获取成功')

# ----------------- 关注 -----------------
@interact_ns.route('/follow')
class FollowAPI(Resource):
    @interact_ns.expect(interaction_model)
    @user_token_required
    def post(self, current_user):
        is_valid, error_msg = validate_required_fields(['target_user_id'])
        if not is_valid:
            return error_response(error_msg, 400)
        data = request.get_json()
        target_user_id = data.get('target_user_id')
        try:
            record = UserInteractionService.follow_user(current_user.id, target_user_id)
            return success_response(record.to_dict(), '关注成功')
        except Exception as e:
            current_app.logger.error(str(e))
            return error_response(str(e), 500)

@interact_ns.route('/follow/<int:record_id>')
class CancelFollowAPI(Resource):
    @user_token_required
    def delete(self, record_id, current_user):
        from app.models.user_behavior import UserBehavior
        rec = UserBehavior.query.get(record_id)
        if not rec or rec.user_id != current_user.id or rec.action != UserInteractionService.ACTION_FOLLOW:
            return error_response('记录不存在', 404)
        from app import db
        db.session.delete(rec)
        db.session.commit()
        return success_response(message='已取消关注')

@interact_ns.route('/followers')
class FollowersAPI(Resource):
    @user_token_required
    def get(self, current_user):
        page = int(request.args.get('page', 1))
        limit = int(request.args.get('limit', 10))
        records, total = UserInteractionService.get_followers(current_user.id, page, limit)
        return success_response({'items': records, 'total': total}, '获取成功')

# ----------------- 拉黑 -----------------
@interact_ns.route('/block')
class BlockAPI(Resource):
    @interact_ns.expect(interaction_model)
    @user_token_required
    def post(self, current_user):
        is_valid, error_msg = validate_required_fields(['target_user_id'])
        if not is_valid:
            return error_response(error_msg, 400)
        data = request.get_json()
        target_user_id = data.get('target_user_id')
        try:
            record = UserInteractionService.block_user(current_user.id, target_user_id)
            return success_response(record.to_dict(), '拉黑成功')
        except Exception as e:
            current_app.logger.error(str(e))
            return error_response(str(e), 500)

@interact_ns.route('/block/<int:record_id>')
class CancelBlockAPI(Resource):
    @user_token_required
    def delete(self, record_id, current_user):
        from app.models.user_behavior import UserBehavior
        rec = UserBehavior.query.get(record_id)
        if not rec or rec.user_id != current_user.id or rec.action != UserInteractionService.ACTION_BLOCK:
            return error_response('记录不存在', 404)
        from app import db
        db.session.delete(rec)
        db.session.commit()
        return success_response(message='已取消拉黑')

# 注册命名空间
api.add_namespace(interact_ns) 